<template>
  <div class="recommendations">
    <div class="recommendations-container">
      <div class="section-header">
        <h2 class="section-title">小助推荐</h2>
        <div class="section-actions">
          <span class="refresh-btn" @click="refreshCourses">🔄 换一批</span>
        </div>
      </div>

      <div class="recommendations-grid">
        <div class="recommendation-item" v-for="(course, index) in videoDatas" :key="index" :ref="setThumbnailRef" @click="goToVideo(course)">
          <div class="course-thumbnail">
            <div class="course-image">
              <div class="play-overlay">
                <!-- <div class="play-icon">▶</div> -->
                 <keep-alive>
                  <mini-video-player  v-if="hoverStates[index]"  :data="course" @timeupdateOther="onTimeUpdate" />
                  <template v-else>
                    <miku-image class="size-full" video :res-id="course.bannerId" draggable="false" />
                  </template>
                </keep-alive>
              </div>
            </div>
            <div class="course-duration">{{ displayDuration(course?.duration ?? 0*1000) }}</div>
          </div>
          <div class="course-info">
            <h3 class="course-title">{{ course.title }}</h3>
            <div class="course-meta">
              <span class="course-views">{{ course.plays }}</span>
              <span class="course-date">{{ course.dynamic.publishTimeStr }}</span>
            </div>
            <div class="course-status">
              <span class="status-text">{{ course.shares }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import videoApi from '@/apis/video';
import { displayDuration } from '@/utils/common';
import { el } from 'element-plus/es/locale';
// const pageSize = ref(12);
// const { state, execute, isLoading } = useAsyncState(()=>videoApi.getRecommend({ 
//   size: pageSize.value
// }), null, { 
//   resetOnExecute: false, 
// })
const thumbnailRefs = ref<HTMLElement[]>([])
const hoverStates = ref<boolean[]>([])
const videoDatas = ref<any[]>([]) // 展示的数据集
const showChanges = ref(false)
const setThumbnailRef = (el: HTMLElement | null) => {
  if (el) thumbnailRefs.value.push(el)
}

// 添加时间记录
const courseTimes = ref<Record<string, number>>({})
// 修改时间更新函数
const onTimeUpdate = (time: number, value: { sid: string }) => {
  courseTimes.value[value.sid] = time
}
// 生成视频链接
const generateVideoUrl = (course: object) => {
  let url = '/video/' + course.sid
  const currentTime = courseTimes.value[course.sid] || 0
  
  if (currentTime >= 3) {
    url += '#time' + currentTime
  }
  return url
}


onMounted(() => {
  
  hoverStates.value = new Array(thumbnailRefs.value.length).fill(false)
  
  thumbnailRefs.value.forEach((el, index) => {
    const isHovered = useElementHover(el, { 
      delayEnter: 200, 
      delayLeave: 200 
    })
    
    watch(isHovered, (value) => {
      hoverStates.value[index] = value
    })
  })
  hottestPlays()
})
// 监听state变化初始化
// watch(() => state.value, (newVal) => {
//   if (newVal) {
//     // 默认显示前四条
//     hottestPlays()
//   }
// }, { immediate: true })

onBeforeUpdate(() => {
  thumbnailRefs.value = []
})

const  hottestPlays = async () => { 
  const datas = await videoApi.getRecommendVideo()
  // console.log('数据为=====',datas)
  // if (!state.value) return
  // 直接取前4条
  if(datas){
    videoDatas.value = datas.records
  }
  // videoDatas.value = state.value.slice(0, 4)
}
// 取后4条数据
// const newestRelease = () => { 
// if (!state.value) return
//   // 取最后6条（倒序排列）
//   videoDatas.value = [...state.value].reverse().slice(0, 4)
// }

//点击视频
const  goToVideo = (value: Object) => {
  const url = generateVideoUrl(value)
  window.open(url, '_blank')
}

// 定义课程数据类型接口
interface Course {
  title: string;
  duration: string;
  views: string;
  date: string;
  status: string;
}

// 推荐课程数据
const recommendedCourses = ref<Course[]>([
  {
    title: '总第9课——西大数信教学学堂',
    duration: '05:43',
    views: '65',
    date: '6-11',
    status: '99%的人都看了'
  },
  {
    title: '总第9课——西大数信教学学堂',
    duration: '04:30',
    views: '65',
    date: '6-11',
    status: '99%的人都看了'
  },
  {
    title: '总第9课——西大数信教学学堂',
    duration: '04:05',
    views: '65',
    date: '6-11',
    status: '99%的人都看了'
  },
  {
    title: '总第9课——西大数信教学学堂',
    duration: '05:28',
    views: '65',
    date: '6-11',
    status: '99%的人都看了'
  }
]);

// 模拟刷新课程的方法
const refreshCourses = () => {
  // 实际项目中这里可能会调用API获取新数据
  // 这里仅做示例，随机修改现有数据
  // recommendedCourses.value = recommendedCourses.value.map(course => ({
  //   ...course,
  //   title: `总第${Math.floor(Math.random() * 20)}课——西大数信教学学堂`,
  //   views: `${Math.floor(Math.random() * 100)}`
  // }));
  showChanges.value = !showChanges.value
  hottestPlays()
  // if(showChanges.value){
  //   newestRelease()
  // }else{
  //   hottestPlays()
  // }
};
</script>

<style scoped>
/* 样式部分保持不变 */
.recommendations {
  background: #fff;
  padding: 40px 0;
}

.recommendations-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin: 0;
}

.section-actions {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: #f0f0f0;
  color: #666;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
}

.refresh-btn:hover {
  background: #e0e0e0;
  color: #333;
}

.recommendations-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
}

.recommendation-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
}

.recommendation-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.course-thumbnail {
  position: relative;
  height: 160px;
  background: #f5f5f5;
}

.course-image {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 1;
  transition: all 0.3s ease;
}

.recommendation-item:hover .play-overlay {
  background: rgba(0, 0, 0, 0.3); /* 悬浮时添加遮罩 */
}

.play-icon {
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: #333;
}

.course-duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.course-info {
  padding: 15px;
}

.course-title {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.course-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.course-status {
  margin-top: 8px;
}

.status-text {
  display: inline-block;
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .section-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .recommendations-grid {
    grid-template-columns: 1fr;
  }
}
</style>